package com.fy.login;

import com.fy.login.internal.MetadataCallback;

import javax.security.auth.callback.*;
import java.io.IOException;

/**
 * @author zhufeifei 2022/8/7
 **/

public class SimpleCallbackHandler implements CallbackHandler {

    protected final String username;
    protected final char[] password;
    protected final Role role;

    public SimpleCallbackHandler(Role role, String username, char[] password) {
        this.username = username;
        this.password = password;
        this.role = role;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        for (Callback c : callbacks) {
            if (c instanceof NameCallback) {
                ((NameCallback) c).setName(this.username);
            } else if (c instanceof PasswordCallback) {
                ((PasswordCallback) c).setPassword(this.password);
            } else if (c instanceof RoleCallback) {
                ((RoleCallback) c).setRole(this.role);
            } else if (c instanceof MetadataCallback) {
                ((MetadataCallback<BaseMetadata>) c).setMetadata(new BaseMetadata(this.role, this.username));
            }
        }
    }
}
